package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }

    @Override
    public void save(Category category) {
        //补齐参数
        category.setId(IdUtil.getSnowflake(1,1).nextId());

        /*//t/odo  临时写死
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());

        category.setCreateUser(1L);
        category.setUpdateUser(1L);*/

        //调用mapper保存
        categoryMapper.save(category);
    }

    @Override
    public void update(Category category) {
       /* //1.补齐参数
        //todo 临时写死
        category.setUpdateUser(1L);
        category.setUpdateTime(new Date());*/

        //2.调用mapper更新
        categoryMapper.update(category);
    }

    //id ---category的id  这个版本也行,但是不规范
   /* @Override
    public ResultInfo deleteById(long id) {
        //1. 根据分类id去菜品表中统计此分类id下的菜品数量,如果数量>0,就返回提示
        Integer num1 = categoryMapper.countDishByCategoryId(id);
        if(num1>0){
            return ResultInfo.error("此分类下存在菜品,不能删除");
        }
        //2. 根据分类id去套餐表中统计此分类id下的套餐数量,如果数量>0,就返回提示
        Integer num2 = categoryMapper.countSetmealByCategoryId(id);
        if(num1>0){
            return ResultInfo.error("此分类下存在菜品,不能删除");
        }
        //3. 根据分类id从分类表中删除
        categoryMapper.delete(id);
        return ResultInfo.success(null);
    }
*/

    //id ---category的id
   @Override
    public void deleteById(long id) {
        //1. 根据分类id去菜品表中统计此分类id下的菜品数量,如果数量>0,就返回提示
        Integer num1 = categoryMapper.countDishByCategoryId(id);
        if(num1>0){
            throw new CustomException("此分类下存在菜品,不能删除");
        }
        //2. 根据分类id去套餐表中统计此分类id下的套餐数量,如果数量>0,就返回提示
        Integer num2 = categoryMapper.countSetmealByCategoryId(id);
        if(num1>0){
            throw new CustomException("此分类下存在菜品,不能删除");
        }
        //3. 根据分类id从分类表中删除
        categoryMapper.delete(id);
    }
}
